//
//  SelectFieldViewController.m
//  MClient
//
//  Created by  史正烨 on 09-10-26.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SelectFieldViewController.h"
#import "EditFormController.h"
#import "CustomFormController.h"

@interface SelectFieldViewController (Private)
//NSMutableArray *selectedItems;
- (Boolean)isSingleSelect;
@end

@implementation SelectFieldViewController
@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize itemList;
@synthesize datas;
@synthesize fieldName;
@synthesize selectedItems;


- (void)viewDidLoad {
	[super viewDidLoad];
	
	self.title = [self.field objectForKey:@"lbl"];	
	if (![self isSingleSelect]) {
		[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
	}
	[self leftBarButton:@"取消" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	
	self.selectedItems = [[NSMutableArray alloc]init];
	
	NSString *fieldValue = [fieldData objectForKey:@"value"];
	if (fieldValue != nil) {
		NSArray *values = [fieldValue componentsSeparatedByString:@","];
		for (NSString *value in values) {
			if ([value isEqualToString:@""]) {
				continue;
			}
			[selectedItems addObject:value];
		}
	}
	
	for(NSMutableDictionary *item in itemList) {
		if ([selectedItems containsObject:[item objectForKey:@"v"]]) {
			[item setObject:@"1" forKey:@"selected"];
		}
		else {
			[item setObject:@"0" forKey:@"selected"];
		}			
	}
	// 用图片做窗口背景，tableview背景色透明
	self.tableview.backgroundColor = [UIColor clearColor];
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-03-06.html";
}


- (void)dealloc {
	[fieldData release];
	[valueField release];
	[field release];	
	[itemList release];
	[datas release];
	[fieldName release];
	[selectedItems release];
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [itemList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selectCellIdentifier"];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"selectCellIdentifier"] autorelease];
		cell.textLabel.font = [UIFont systemFontOfSize:16];
		cell.textLabel.numberOfLines = 2;
	}
	int row = [indexPath row];
	if ([[itemList objectAtIndex:row] objectForKey:@"icon"]) {
		NSString *icon = [[itemList objectAtIndex:row] objectForKey:@"icon"];
		cell.imageView.image =[MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
	}
	cell.textLabel.text = [[itemList objectAtIndex:row] objectForKey:@"t"];
	NSString *selected = [[itemList objectAtIndex:row] objectForKey:@"selected"];
	if ([selected isEqualToString:@"1"])
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	else
		cell.accessoryType = UITableViewCellAccessoryNone;
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell;
	NSMutableDictionary *item;
	
	if ([self isSingleSelect]) {
		item = [itemList objectAtIndex:[indexPath row]];
		
		NSString *labelString = [item objectForKey:@"t"] == nil?@"":[item objectForKey:@"t"];	
		NSString *valueString = [item objectForKey:@"v"] == nil?@"":[item objectForKey:@"v"];
		
		for (NSMutableDictionary *it in itemList) {
			[it setObject:[NSNumber numberWithBool:NO] forKey:@"s"];
		}
		[item setObject:[NSNumber numberWithBool:YES] forKey:@"s"];
		
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		if (![item objectForKey:@"icon"]) {
			self.valueField.text = labelString;
		}
				
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];

		UIViewController *controller = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		if ([controller isMemberOfClass:[EditFormController class]]) {
			[(EditFormController *)controller doCalcAction:((MCTextField*)valueField.control)];
		}
		if([field objectForKey:@"autobackfill"] != nil) {
			NSString *invalid = [field objectForKey:@"invalid"];
			if(invalid == nil || ![valueString isEqualToString:invalid]) {
				NSString *autobackfill = [field objectForKey:@"autobackfill"];
				
				if ([controller isMemberOfClass:[EditFormController class]]) {
					[(EditFormController *)controller autoBackFill:autobackfill fieldValue:labelString];
				} else if ([controller isMemberOfClass:[CustomFormController class]]) {
					[(CustomFormController *)controller autoBackFill:autobackfill fieldValue:labelString];
				} 
			}
		}
		
		[self.navigationController popViewControllerAnimated:YES];
	}
	else {
		item = [itemList objectAtIndex:[indexPath row]];
		cell = [tableView cellForRowAtIndexPath:indexPath];
		if (cell.accessoryType == UITableViewCellAccessoryNone) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			[item setObject:@"1" forKey:@"selected"];
			[item setObject:[NSNumber numberWithBool:YES] forKey:@"s"];
		}
		else {
			cell.accessoryType = UITableViewCellAccessoryNone;
			[item setObject:@"0" forKey:@"selected"];
			[item setObject:[NSNumber numberWithBool:NO] forKey:@"s"];
		}
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark ---- 按钮事件处理方法 ----
- (void) selectAction: (id) sender {
	NSString *labelString = @"";	
	NSString *valueString = @"";
	bool isIcon = NO;
	for(NSMutableDictionary *item in itemList) {
		if ([item objectForKey:@"icon"]) {
			isIcon = YES;
		}
		if ([[item objectForKey:@"selected"] isEqualToString:@"1"]) {
			labelString = [labelString stringByAppendingFormat:@"%@,",[item objectForKey:@"t"] == nil?@"":[item objectForKey:@"t"]];
			valueString = [valueString stringByAppendingFormat:@"%@,",[item objectForKey:@"v"] == nil?@"":[item objectForKey:@"v"]];
		}
	}
	if ([labelString length] > 0) {
		labelString = [labelString substringToIndex:[labelString length] - 1];
	}
	if ([valueString length] > 0) {
		valueString = [valueString substringToIndex:[valueString length] - 1];
	}
	
	[self.fieldData setObject:valueString forKey:@"value"];
	[self.fieldData setObject:labelString forKey:@"lbl"];
	if (!isIcon) {
		self.valueField.text = labelString;
	}
	
	NSMutableDictionary *fieldLabelData = [[NSMutableDictionary alloc]init];
	[fieldLabelData setObject:labelString forKey:@"value"];
	[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
	
	[self.navigationController popViewControllerAnimated:YES];
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (Boolean)isSingleSelect {
	NSString *fieldType = [field objectForKey:@"type"];
	if ([fieldType isEqualToString:@"I"] || [fieldType isEqualToString:@"L"]) {
		return NO;
	}
	return YES;
}

@end

@interface PopUpSelectFieldViewController (Private)
//NSMutableArray *selectedItems;
- (Boolean)isSingleSelect;
@end

@implementation PopUpSelectFieldViewController
@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize itemList;
@synthesize datas;
@synthesize fieldName;
@synthesize selectedItems;


- (void)viewDidLoad {
	[super viewDidLoad];
}

- (void)show:(UINavigationController*)naviController
{
	if ([naviController.visibleViewController respondsToSelector:@selector(keyboardDidHidden:)]) {
		[naviController.visibleViewController performSelector:@selector(keyboardDidHidden:) withObject:nil];
	}
	[naviController pushViewController:self animated:NO];
	
	self.selectedItems = [[NSMutableArray alloc]init];
	
	NSString *fieldValue = [fieldData objectForKey:@"value"];
	if (fieldValue != nil) {
		NSArray *values = [fieldValue componentsSeparatedByString:@","];
		for (NSString *value in values) {
			if ([value isEqualToString:@""]) {
				continue;
			}
			[selectedItems addObject:value];
		}
	}
	
	for(NSMutableDictionary *item in itemList) {
		if ([selectedItems containsObject:[item objectForKey:@"v"]]) {
			[item setObject:@"1" forKey:@"selected"];
		}
		else {
			[item setObject:@"0" forKey:@"selected"];
		}			
	}
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	_foreView.frame = CGRectMake(0, 0, self.width, self.height+20);
    
	_tableView.frame = [self tableViewLocation];
	if (footView) {
		CGRect frame = footView.frame;
		frame.origin.y = CGRectGetMaxY(_tableView.frame);
		footView.frame = frame;
	}
	[UIView commitAnimations]; 
}

- (void)close
{
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(popoutView)];
	[UIView setAnimationDuration:0.3];
	_foreView.frame = CGRectMake(0, CGRectGetHeight(_foreView.frame), CGRectGetWidth(_foreView.frame), CGRectGetHeight(_foreView.frame));
	_tableView.frame = CGRectMake(0, self.height, CGRectGetWidth(_tableView.frame), CGRectGetHeight(_tableView.frame));
	footView.frame = CGRectMake(0, self.height, CGRectGetWidth(footView.frame), CGRectGetHeight(footView.frame));
	[UIView commitAnimations]; 
}

- (CGRect)tableViewLocation {
	if ([itemList count] > 0) {//多选：有选项数据
		CGFloat posY = (self.height-[itemList count]*58 - 12)/2;//huotianjun 将38改为58
		CGFloat height = [itemList count]*58+12;
		if ([self isSingleSelect]) {
			if (posY < 0) {
				posY = 20;
				_tableView.scrollEnabled = YES;
				height = self.height - 70;
				UILabel* view = [[UILabel alloc] initWithFrame:CGRectMake(0, self.height, self.width, 30)];
				view.text = @"上下拖拉可以浏览全部";
				view.textAlignment = UITextAlignmentCenter;
				view.textColor = [UIColor grayColor];
				view.backgroundColor = [UIColor clearColor];
				
				[self.view addSubview:footView = view];
			}
		} else {
			posY = (self.height-[itemList count]*58 - 12 - 60)/2;
			if (posY < 0) {
				posY = 20;
				_tableView.scrollEnabled = YES;
				height = self.height - 100;
				
				UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, self.width, 80)];
				view.backgroundColor = [UIColor clearColor];
				UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width, 20)];
				label.text = @"上下拖拉可以浏览全部";
				label.textAlignment = UITextAlignmentCenter;
				label.textColor = [UIColor grayColor];
				label.backgroundColor = [UIColor clearColor];
				[view addSubview:label];
				[label release];
				
				UIButton* cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
				cancelBtn.tag = -1;
				cancelBtn.frame = CGRectMake(35, 25, 80, 30);
				cancelBtn.autoresizingMask = nTableCellAutoresizingMask;
				[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
				[cancelBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
				[view addSubview:cancelBtn];
				
				UIButton* confirmBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
				confirmBtn.tag = -2;
				confirmBtn.frame = CGRectMake(self.width-80-35, 25, 80, 30);
				confirmBtn.autoresizingMask = nTableCellAutoresizingMask;
				[confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
				[confirmBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
				[view addSubview:confirmBtn];
				
				[self.view addSubview:footView = view];
			} else {
				UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, self.width, 50)];
				view.backgroundColor = [UIColor clearColor];
				UIButton* cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
				cancelBtn.tag = -1;
				cancelBtn.frame = CGRectMake(35, 10, 80, 30);
				cancelBtn.autoresizingMask = nTableCellAutoresizingMask;
				[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
				[cancelBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
				[view addSubview:cancelBtn];
				
				UIButton* confirmBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
				confirmBtn.tag = -2;
				confirmBtn.frame = CGRectMake(self.width-80-35, 10, 80, 30);
				confirmBtn.autoresizingMask = nTableCellAutoresizingMask;
				[confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
				[confirmBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
				[view addSubview:confirmBtn];
				
				[self.view addSubview:footView = view];
			}
		}
		return CGRectMake(0, posY, self.width, height);
	} else {
		_tableView.scrollEnabled = NO;
		return CGRectMake(0, self.height/2+20, self.width, 50);
	}
}

- (void)dealloc {
	[fieldData release];
	[valueField release];
	[field release];	
	[itemList release];
	[datas release];
	[fieldName release];
	[selectedItems release];
	[footView release];
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([itemList count] > 0) {//多选：有选项数据
		selectionType = Selection_HasData;
		return [itemList count];
	} else {
		selectionType = Selection_NoData;
		return 1;//无选项数据，自动添加一项：无数据提示
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selectCellIdentifier"];
	if (cell == nil) {
		//cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"selectCellIdentifier"] autorelease];
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"selectCellIdentifier"] autorelease];
		cell.textLabel.font = [UIFont systemFontOfSize:16];
		cell.textLabel.numberOfLines = 2;
	}
	
	if (selectionType == Selection_NoData) {
		cell.accessoryType = UITableViewCellAccessoryNone;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.textLabel.text = @"无选项数据！";
		cell.textLabel.textColor = [UIColor darkGrayColor];
		cell.textLabel.textAlignment = UITextAlignmentCenter;
	} else  {
		if ([[itemList objectAtIndex:indexPath.row] objectForKey:@"icon"]) {
			NSString *icon = [[itemList objectAtIndex:indexPath.row] objectForKey:@"icon"];
			cell.imageView.image =[MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
		}
		cell.textLabel.text = [[itemList objectAtIndex:indexPath.row] objectForKey:@"t"];
		NSString *selected = [[itemList objectAtIndex:indexPath.row] objectForKey:@"selected"];
		if ([selected isEqualToString:@"1"])
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
		else
			cell.accessoryType = UITableViewCellAccessoryNone;
	}
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell;
	NSMutableDictionary *item;
	
	if (selectionType == Selection_NoData) {
		[self close];
		return;
	}
	if ([self isSingleSelect]) {
		item = [itemList objectAtIndex:[indexPath row]];
		
		NSString *labelString = [item objectForKey:@"t"] == nil?@"":[item objectForKey:@"t"];	
		NSString *valueString = [item objectForKey:@"v"] == nil?@"":[item objectForKey:@"v"];
		
		for (NSMutableDictionary *it in itemList) {
			[it setObject:[NSNumber numberWithBool:NO] forKey:@"s"];
		}
		[item setObject:[NSNumber numberWithBool:YES] forKey:@"s"];
		
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		if (![item objectForKey:@"icon"]) {
			self.valueField.text = labelString;
		}
		
		NSMutableDictionary *fieldLabelData = [[NSMutableDictionary alloc]init];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		UIViewController *controller = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		if ([controller isMemberOfClass:[EditFormController class]]) {
			[(EditFormController *)controller doCalcAction:((MCTextField*)valueField.control)];
		}
		if([field objectForKey:@"autobackfill"] != nil) {
			NSString *invalid = [field objectForKey:@"invalid"];
			if(invalid == nil || ![valueString isEqualToString:invalid]) {
				NSString *autobackfill = [field objectForKey:@"autobackfill"];
				
				if ([controller isMemberOfClass:[EditFormController class]]) {
					[(EditFormController *)controller autoBackFill:autobackfill fieldValue:labelString];
				} else if ([controller isMemberOfClass:[CustomFormController class]]) {
					[(CustomFormController *)controller autoBackFill:autobackfill fieldValue:labelString];
				} 
			}
		}
		[self close];
	}
	else {
		item = [itemList objectAtIndex:[indexPath row]];
		cell = [tableView cellForRowAtIndexPath:indexPath];
		if (cell.accessoryType == UITableViewCellAccessoryNone) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			[item setObject:@"1" forKey:@"selected"];
			[item setObject:[NSNumber numberWithBool:YES] forKey:@"s"];
		}
		else {
			cell.accessoryType = UITableViewCellAccessoryNone;
			[item setObject:@"0" forKey:@"selected"];
			[item setObject:[NSNumber numberWithBool:NO] forKey:@"s"];
		}
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark ---- 按钮事件处理方法 ----
- (void) selectAction: (id) sender {
	NSString *labelString = @"";	
	NSString *valueString = @"";
	bool isIcon = NO;
	for(NSMutableDictionary *item in itemList) {
		if ([item objectForKey:@"icon"]) {
			isIcon = YES;
		}
		if ([[item objectForKey:@"selected"] isEqualToString:@"1"]) {
			labelString = [labelString stringByAppendingFormat:@"%@,",[item objectForKey:@"t"] == nil?@"":[item objectForKey:@"t"]];
			valueString = [valueString stringByAppendingFormat:@"%@,",[item objectForKey:@"v"] == nil?@"":[item objectForKey:@"v"]];
		}
	}
	if ([labelString length] > 0) {
		labelString = [labelString substringToIndex:[labelString length] - 1];
	}
	if ([valueString length] > 0) {
		valueString = [valueString substringToIndex:[valueString length] - 1];
	}
	
	[self.fieldData setObject:valueString forKey:@"value"];
	[self.fieldData setObject:labelString forKey:@"lbl"];
	if (!isIcon) {
		self.valueField.text = labelString;
	}
	
	NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
	[fieldLabelData setObject:labelString forKey:@"value"];
	[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
	
	//刷新编辑页面
	EditFormController *editFormController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
	[editFormController reloadData];
	
	[self close];
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (Boolean)isSingleSelect {
	NSString *fieldType = [field objectForKey:@"type"];
	if ([fieldType isEqualToString:@"I"] || [fieldType isEqualToString:@"L"]) {
		return NO;
	}
	return YES;
}
@end
